#include "widget.h"
#include "ui_server.h"


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    /* 设置窗口标题 */
    this->setWindowTitle("Server");

    /* 初始化端口和IP */
    ui->ip->setText("127.0.0.1");
    ui->port->setText("8888");
    /* 初始化服务器对象 */
    this->tcpServer = new QTcpServer(this);
    /* 设置监听ip和port */
    this->tcpServer->listen(QHostAddress(ui->ip->text()),
                            ui->port->text().toInt());
    /* 当有连接时会接受到信号 */
    connect(tcpServer, &QTcpServer::newConnection, [=](){
        this->tcpSocket = tcpServer->nextPendingConnection();
        ui->recv_buffer->setText("新的连接......");

        connect(tcpSocket, &QTcpSocket::readyRead, [=](){
            QString string = tcpSocket->readAll();
            ui->recv_buffer->append(string);
        });

    });

    connect(ui->send, &QPushButton::clicked, [=](){
        if (this->tcpSocket != nullptr) {
            tcpSocket->write(ui->send_buffer->toPlainText().toUtf8());
            ui->send_buffer->clear();
        }
    });

}

Widget::~Widget()
{
    delete ui;
}

